/*
 * #%L
 * SwiftUICommonUtilities
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
package com.linkwithweb.products.swiftui.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Spring Service Locator
 * @author ashwin
 *
 */
public class ServiceLocator implements ApplicationContextAware {
	protected final Log logger = LogFactory.getLog(getClass());
	private static ApplicationContext applicationContext = null;

	/* (non-Javadoc)
	 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
	 */
	public void setApplicationContext(ApplicationContext applicationContext) {
		logger.debug("***Spring application context Acquired****");
		ServiceLocator.applicationContext = applicationContext;
	}

	/**
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * This method assumes that the bean created has the same name as the class.
	 * 
	 * 
	 * @param <T>
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getService(Class<T> clazz) {
		if (clazz == null) {
			return null;
		}

		int servicePackageLength = clazz.getPackage().getName().length() + 1;

		StringBuffer serviceName = new StringBuffer(clazz.getName().substring(servicePackageLength));

		serviceName.setCharAt(0, Character.toLowerCase(serviceName.charAt(0)));
				
		return (T) getService(serviceName.toString());
	}

	/**
	 * @param beanName
	 * @return
	 */
	public static Object getService(String beanName) {
		if (applicationContext == null) {			
			return null;
		}

		Object o = applicationContext.getBean(beanName);
		return o;
	}
	
	
	
}

